// pages/JX/detail/detail.js
import S_request from '../../../utils/requestService.js';
import CONFIG from '../../../config.js';
import * as utils from '../../../utils/util.js';
const app = getApp()
let id = 0
Page({

  /**
   * 页面的初始数据
   */
  data: {
    info: {},
    modalObj: {},
    isShowkj: false,
    isShowZj: false,
    isShowZz: false,
    swiperCurrent: 0, //当前的位置
    isShowAuth: true,
    autoplay: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    id = options.id;
    this.getDetailInfo(id)
    this.getSetting();
    // this.test();
  },
  test: function() {
    this.data.modalObj.isZj = true;
    this.data.modalObj.winList = []
    this.setData({
      isShowkj: false,
      isShowZj: true,
      modalObj: this.data.modalObj
    })
  },
  getDetailInfo: function(id) {
    S_request.jx.getDetailInfo(id, (result) => {
      result.open_time1 = utils.formatTime(result.open_time, 3);
      //pay_status表示类型 0：系统随机 1：分享最多者获得
      //join表示自己是否参与 0：未参与抽奖 1：已参与
      if (result.pay_status == 0) {
        result.txt = '系统随机抽取'
        result.sign = "邀请参与抽奖的人数越多，中奖率越高"
      } else {
        result.txt = '邀请最多者获得'
        result.sign = "邀请参与抽奖的人数最多者，直接获得该奖品。"
      }
      //gys[game_type_id] 1:小程序跳转 2：淘宝口令 3：二维码图片
      result.gys.gys_type = "../image/icon_" + result.gys.game_type_id + ".png"
      //如果玩家参与了抽奖
      if (result.status == 0) { //未开奖
        if (result.userinfo.count == 0) { //未参与抽奖，显示立即参与
          result.joinTitle = '参与抽奖'
          result.joinStyle = 'border:0; background-color:#d3ae79;'
        } else {
          result.btnTitle = '待开奖'
          result.btnStyle = 'border:0; background-color:#0f9134;'
          result.joinTitle = '待开奖'
          result.joinStyle = 'background-color:#e4d2b7;'
        }
      } else { //已开奖
        result.btnTitle = '已开奖'
        result.btnStyle = 'border:0; background-color:#9a9898;'
        result.joinTitle = '已开奖'
        result.joinStyle = 'background-color:#9a9898;'
      }
      //已开奖 && 自己参与了抽奖
      if (result.status == 1 && result.userinfo.count != 0) {
        let now_time = new Date().getTime();
        //一天86400秒*1000*3
        if (now_time - result.open_time * 1000 < 86400000 * 3) { //超过三天，不播放动画
          let tempStr = wx.getStorageSync('kjIds');
          if (tempStr != '') {
            let idArr = tempStr.split(",");
            let tempId = -1
            for (let i = 0; i < idArr.length; i++) {
              if (idArr[i] == result.id) { //已经播放过动画
                tempId = idArr[i]
                break;
              }
            }
            if (tempId == -1) {
              this.showKjAni(result.me, result.win, result.jindu); //显示开奖动画
              wx.setStorageSync('kjIds', tempStr + result.id + ",")
            }
          } else {
            this.showKjAni(result.me, result.win, result.jindu); //显示开奖动画
            wx.setStorageSync('kjIds', tempStr + result.id + ",")
          }
        }
        if (result.me == 1) {
          result.btnTitle = '领取奖品'
          result.btnStyle = 'border:0; background-color:#f77e2e;'
        }
      }
      if (parseInt(result.jindu) > 0) { //领取奖品之后 "领取奖品"按钮隐藏
        result.btnTitle = '';
        result.btnStyle = 'display:none'
      }
      if (result.status == 1) {
        this.kjUI(result);
      }
      this.setData({
        info: result
      })
      if (result.userinfo.count != 0 && result.status == 0 && this.data.autoplay) { //已参与且未开奖
        this.setData({
          autoplay: true
        })
      }
    })
  },
  //参与抽奖
  patiCJ: function() {
    let info = this.data.info;
    if (info.status == 1) return;
    let id = info.id;
    S_request.jx.joinCJ(id, (result) => {
      // wx.showModal({
      //   title: '提示',
      //   content: '参与成功',
      //   showCancel: false
      // })
      this.data.autoplay = true; //参与成功后， 2s滑动到右侧邀请参与界面
      this.getDetailInfo(id);
    })
  },
  openGYS: function() {
    let type = this.data.info.gys.game_type_id;
    let param = 'formId=0' + '&eventid=' + type + "&program_id=" + this.data.info.gys_id;
    if (type == 1) { //跳转到小程序
      S_request.jx.tongJiNum(id, param, (result) => {
        console.log("data====" + result);
      })
      return;
    } else if (type == 3) { //二维码
      wx.previewImage({
        current: this.data.info.gys.icode, // 当前显示图片的http链接   
        urls: [this.data.info.gys.icode] // 需要预览的图片http链接列表   
      })
      return;
      // this.data.modalObj.name = this.data.info.gys.game_name;
      // this.data.modalObj.icode = this.data.info.gys.icode;
      // this.data.modalObj.detail = this.data.info.gys.game_poster;
    } else if (type == 2) { //口令
      this.data.modalObj.name = this.data.info.gys.game_name;
      this.data.modalObj.title = this.data.info.gys.game_poster;
      this.data.modalObj.detail = this.data.info.gys.taobao_wenzi;
    }
    this.data.modalObj.type = type;
    this.setData({
      isShowZz: true,
      modalObj: this.data.modalObj
    })
  },
  copySuccess: function() {
    let param = 'formId=0' + '&eventid=2' + "&program_id=" + this.data.info.gys_id;
    S_request.jx.tongJiNum(id, param, (result) => {
      console.log("data====" + result);
    })
  },
  getReward: function() {
    let detailInfo = this.data.info
    // let id = e.currentTarget.dataset.id;
    if (detailInfo.status == 1 && detailInfo.userinfo.count != 0 && detailInfo.me == 1) {
      wx.navigateTo({
        url: '../../Mine/shopExcAddr/shopExcAddr?goodId=' + detailInfo.ids + "&type=" + detailInfo.game_type_id,
      })
    }
  },
  closeZzBtnAc: function() {
    this.setData({
      isShowZz: false
    })
  },
  showKjAni: function(isZj, winList, jindu) {
    setTimeout(function() {
      this.setData({
        isShowkj: true
      })
    }.bind(this), 500)
    setTimeout(function() {
      this.data.modalObj.isZj = isZj;
      this.data.modalObj.winList = winList
      this.data.modalObj.jindu = parseInt(jindu)
      this.setData({
        isShowkj: false,
        isShowZj: true,
        modalObj: this.data.modalObj
      })
    }.bind(this), 3000)
  },
  closeZjBtnAc: function() {
    this.setData({
      isShowZj: false
    })
  },
  allUsers: function() {
    wx.navigateTo({
      url: '../partiUsers/partiUsers?id=' + this.data.info.id + '&treasure_id=' + this.data.info.userinfo.treasure_id + "&image_url=" + this.data.info.shareicon + '&game_name=' + this.data.info.game_name,
    })
  },
  //开奖界面显示
  kjUI: function(result) {
    let zjInfo = {}
    if (result.userinfo.count == 0) { //没有参与抽奖
      zjInfo.icon = '../image/zj_icon.png'
      zjInfo.title = '恭喜以下小伙伴们'
      zjInfo.titleStyle = 'color:#d1594e'
    } else {
      if (result.me) { //中奖
        zjInfo.icon = '../image/zj_icon.png'
        zjInfo.title = '恭喜，您已中奖'
        zjInfo.titleStyle = 'color:#d1594e'
      } else {
        zjInfo.icon = '../image/zj_icon.png'
        zjInfo.title = '差一点点就中奖了，继续努力！'
        zjInfo.titleStyle = 'color:#333'
      }
    }
    if (result.win.length == 1) {
      zjInfo.bodyStyle = 'width:154rpx;'
    } else if (result.win.length == 2) {
      zjInfo.bodyStyle = 'width:308rpx;'
    } else {
      zjInfo.bodyStyle = 'width:462rpx;'
    }
    this.setData({
      zjInfo: zjInfo
    })
  },
  toJX: function() {
    wx.switchTab({
      url: '../index/index'
    })
  },
  toRank: function() {
    wx.navigateTo({
      url: '../rank/rank?id=' + this.data.info.id + '&treasure_id=' + this.data.info.userinfo.treasure_id + "&image_url=" + this.data.info.shareicon + '&game_name=' + this.data.info.game_name
    })
  },
  getSetting: function() {
    let self = this;
    // 获取用户信息
    wx.getSetting({
      success: res => {
        var authSetting = res.authSetting;
        if (authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          app.globalData.isAuthorize = true;
        } else if (authSetting['scope.userInfo'] == false) {
          // 用户已拒绝授权，再调用相关 API 或者 wx.authorize 会失败，需要引导用户到设置页面打开授权开关
          app.globalData.isAuthorize = false;
        } else {
          // 未询问过用户授权，调用相关 API 或者 wx.authorize 会弹窗询问用户
          app.globalData.isAuthorize = false;
        }
        self.isShowLogin();
      }
    })
  },
  isShowLogin: function() {
    console.log("isAuthorize===" + app.globalData.isAuthorize)
    if (app.globalData.isAuthorize) {
      this.getUserInfo();
      this.setData({
        isShowAuth: false,
      });
    } else {
      this.setData({
        isShowAuth: true
      });
    }
  },
  getUserInfo: function() {
    wx.getUserInfo({
      success: res => {
        // 可以将 res 发送给后台解码出 unionId
        app.globalData.userInfo = res.userInfo;
        this.setData({
          userinfo: app.globalData.userInfo,
        });
        S_request.jx.updateUserInfo(res.userInfo, (result) => {
          // console.log("更新与用户信息成功====" + JSON.stringify(result));
          app.globalData.goldnum = result.goldcoin;
        })
      }
    })
  },
  onGotUserInfo: function(e) {
    let self = this;
    console.log(e.detail.errMsg)
    console.log(e.detail.userInfo)
    console.log(e.detail.rawData)
    if (!e.detail.userInfo) return;
    app.globalData.userInfo = e.detail.userInfo;
    let userInfo = e.detail.userInfo;
    S_request.jx.updateUserInfo(userInfo, (result) => {
      // console.log("更新与用户信息成功====" + JSON.stringify(result));
      app.globalData.isAuthorize = true;
      self.setData({
        isShowAuth: false
      });
    })
  },
  formSubmit: function(e) {
    let formId = e.detail.formId;
    console.log('form发生了submit事件，携带数据为：', e.detail.value + ", " + e.detail.formId)
    let id = this.data.info.id;
    console.log("detail id====" + id + ",formId===" + formId);
    let param = 'formId=' + formId;
    S_request.jx.tongJiNum(id, param, (result) => {
      console.log("data====" + result);
    })
  },
  saveTxt: function() {
    wx.setClipboardData({
      data: this.data.info.gys.zhanshi_wenzi,
      success: function(res) {
        wx.getClipboardData({
          success: function(res) {　　　　　　　　　　　　　　　　　　　　　}
        })
      }
    })
  },
  changeCurrent: function(e) {
    let current = e.detail.current;
    let source = e.detail.source;
    console.log("source====" + source+",current=="+current)
    //用途： 上下current一样
    if(source == 'touch')  {
      this.setData({
        swiperCurrent: current
      })
    }
    if (current == 1) {
      this.setData({
        autoplay: false
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getDetailInfo(id)
    this.getSetting();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    wx.showShareMenu({
      withShareTicket: false,
      success: function() {}
    });
    let nickname = '亲，'
    if (app.globalData.userInfo != null) {
      nickname = app.globalData.userInfo.nickName;
    }
    let url = encodeURIComponent('/pages/JX/detail/detail?id=' + this.data.info.id)
    let path = CONFIG.SHARE.pathDet + "&url=" + url + '&treasure_id=' + this.data.info.userinfo.treasure_id
    console.log("url===" + path)
    let title = nickname + "邀请您参与【" + this.data.info.game_name + "】免费抽奖"
    
    let obj = { 'pagepath': CONFIG.SHARE.pathDet, 'url': url, 'treasure_id': this.data.info.userinfo.treasure_id }
    S_request.jx.recordShare(this.data.info.userinfo.treasure_id, obj);
    return {
      title: title,
      path: path,
      imageUrl: this.data.info.shareicon,
      success: (res) => { //新版不走回调
        console.log("分享成功")
      }
    }
  }
})